<?php

namespace App\Admin\Controllers\Financial;

use App\Admin\Models\Financial\FinancialProfit;
use App\Store\Models\Account\SiteStore;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Common\Services\CommonExcelExport;
use Maatwebsite\Excel\Facades\Excel;

use App\Admin\Validate\Financial\FinancialProfit as ValidateFinancialFinancialProfit;
class FinancialProfitController extends Controller
{

    public function getsearchdata(Request $request)
    {
        $date_start=strtotime($request->date_start);
        $date_end=strtotime($request->date_end);
        if($date_start<=0 || $date_end<=0){
            return response()->json(['code' => '001', 'msg' => '无效日期']);
        }
        $syear=date('Y',$date_start);
        $smonth=date('m',$date_start);
        $eyear=date('Y',$date_end);
        $emonth=date('m',$date_end);

        if($syear!=$eyear){
            return response()->json(['code' => '001', 'msg' => '不可跨年查询']);
        }


        $searchdata = FinancialProfit::where([['is_del',1],['year',$syear],['month','>=',$smonth],['month','<=',$emonth]])->get()->toArray();

        $searchdatainfo=[];
        for($i=1;$i<=32;$i++){
            $searchdatainfo['data_key_'.$i]=array_sum(array_column($searchdata,'data_key_'.$i));
        }

        if($syear==date('Y')){
            $maxmonth=date('m');
        }else{
            $maxmonth=12;
        }




        $totallist=FinancialProfit::where([['year', $syear],['is_del',1],['month','<=',$maxmonth]])
        ->get()->toArray();
        $totalinfo=[];
        for($i=1;$i<=32;$i++){
            $totalinfo['data_key_'.$i]=array_sum(array_column($totallist,'data_key_'.$i));
        }

        if($request->isexport==1){
            return $this->doexport($searchdatainfo,$totalinfo,$request->date_start,$request->date_end);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['searchdatainfo' => $searchdatainfo,'totalinfo'=>$totalinfo]]);
    }
    public function getinfo(Request $request)
    {
        $date=strtotime($request->date);
        if($date<=0){
            return response()->json(['code' => '001', 'msg' => '无效日期']);
        }
        $year=date('Y',$date);
        $month=date('m',$date);
        $info = FinancialProfit::where(['year' => $year,'is_del'=>1,'month'=>$month])->first();
        if (!$info) {
            return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => [
                'data_key_1' => 0,'data_key_2' => 0,'data_key_3' => 0,'data_key_4' => 0,'data_key_5' => 0,'data_key_6' => 0,'data_key_7' => 0,'data_key_8' => 0,'data_key_9' => 0,'data_key_10' => 0,'data_key_11' => 0,'data_key_12' => 0,'data_key_13' => 0,'data_key_14' => 0,'data_key_15' => 0,'data_key_16' => 0,'data_key_17' => 0,'data_key_18' => 0,'data_key_19' => 0,'data_key_20' => 0,'data_key_21' => 0,'data_key_22' => 0,'data_key_23' => 0,'data_key_24' => 0,'data_key_25' => 0,'data_key_26' => 0,'data_key_27' => 0,'data_key_28' => 0,'data_key_29' => 0,'data_key_30' => 0,'data_key_31' => 0,'data_key_32' => 0
            ]]]);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    public function saveinfo(Request $request)
    {
        $data_arr=['year', 'month','remark'];
        for($i=1;$i<=32;$i++){
            $data_arr[]='data_key_'.$i;
        }
        $req_data = $request->only($data_arr);


        $Validate = new ValidateFinancialFinancialProfit;
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

//        $info = FinancialProfit::where(['year' => $req_data['year'],'is_del'=>1,'month'=>$req_data['month']])->first();
//        if (!$info) {
//            return response()->json(['code' => '001', 'msg' => '参数错误']);
//        }
//        $data=$req_data;
//        unset($data['year']);
//        unset($data['month']);
//        $data['update_at']=time();
//        FinancialProfit::where(['year' => $req_data['year'],'is_del'=>1,'month'=>$req_data['month']])->update($data);
//        return response()->json(['code' => '000', 'msg' => '操作成功']);
        FinancialProfit::updateOrInsert(['year' => $req_data['year'], 'is_del'=>1, 'month'=>$req_data['month']], $req_data);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }



    public function doexport($info,$totalinfo,$date_start,$date_end)
    {
        $title_arr=['1'=>'一、营业收入','2'=>'减：营业成本','3'=>'税金及附加','4'=>'其中：消费税','5'=>'营业税','6'=>'城市维护建设费',
            '7'=>'资源税','8'=>'土地增值税','9'=>'城镇土地使用税、房产税、车船税、印花税','10'=>'教育费附加、矿产资源补偿费、 排污费',
            '11'=>'销售费用','12'=>'其中：商品维修费','13'=>'广告费和业务宣传费','14'=>'管理费用','15'=>'其中：开办费','16'=>'业务招待费',
            '17'=>'研究费用','18'=>'财务费用','19'=>'其中：利息费用（收入以“-”号填列）','20'=>'加：投资收益（损失以“-”号填列）',
            '21'=>'二、营业利润（亏损以“-”号填列）','22'=>'加：营业外收入','23'=>'其中：政府补助','24'=>'减：营业外支出','25'=>'其中：坏账损失',
            '26'=>'无法收回的长期债券投资损失','27'=>'无法收回的长期股权投资损失','28'=>'自然灾害等不可抗力因素造成的损失','29'=>'税收滞纳金','30'=>'三、利润总额（亏损总额以“-”号填列）','31'=>'所得税费用','32'=>'四、净利润（净亏损以“-”号填列）'
        ];
        $datawith = [
            'A' => '50', 'B' => '8', 'C' => '30', 'D' => '30'
        ];
        $exceldata = [];
//        $store_name = SiteStore::where('id','=',$store_id)->value('store_name');
        $row = [
            ['title'=>'利润表'],
            [$date_start.' - '.$date_end],
            [
                'title' => '项目',
                'keyindex' => '行次',
                'money' => '本月金额',
                'totalmoney' => '本年累计金额',
            ]
        ];
        for($i=1;$i<=32;$i++){
            $exceldata[]=[
                'title' => $title_arr[$i],
                'keyindex' => $i,
                'money' => $info['data_key_'.$i]/100,
                'totalmoney' => $totalinfo['data_key_'.$i]/100,
            ];
        }
        $filename = '利润表信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata,$datawith), $filename);
    }
}
